package com.example.jobback.service.recruiter.impl;

import com.alibaba.fastjson.JSON;
import com.example.jobback.config.AuthConfig;
import com.example.jobback.mapper.InterestMapper;
import com.example.jobback.mapper.RecruiterMapper;
import com.example.jobback.po.Recruiter;
import com.example.jobback.po.Seeker;
import com.example.jobback.po.User;
import com.example.jobback.req.recruiter.seeker.RCrossGetGoodSeekerListReq;
import com.example.jobback.req.seeker.genius.SCrossGetGoodSeekerListReq;
import com.example.jobback.resp.recruiter.interest.InterestedSeekerResp;
import com.example.jobback.resp.recruiter.seeker.RCrossGetGoodSeekerResp;
import com.example.jobback.resp.recruiter.seeker.RCrossGetGoodSeekersResp;
import com.example.jobback.resp.seeker.genius.SCrossGetGoodSeekerResp;
import com.example.jobback.resp.seeker.genius.SCrossGetGoodSeekersResp;
import com.example.jobback.result.Result;
import com.example.jobback.service.common.UserCommonService;
import com.example.jobback.service.recruiter.RecruiterSeekerService;
import com.example.jobback.service.seeker.SeekerCrossService;
import com.example.jobback.util.CrossServiceInvoker;
import com.example.jobback.util.PhoneNumberUtils;
import com.example.jobback.util.TLUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.example.jobback.util.RedisConstants.RECRUITER_KEY;
import static com.example.jobback.util.RedisConstants.RECRUITER_TTL;

/**
 * @ClassName: RecruiterSeekerServiceImpl
 * @Description:聘者-推荐牛人服务接口实现类
 * @Author: lhb
 * @Date: 2025/7/9
 */
@Service
public class RecruiterSeekerServiceImpl implements RecruiterSeekerService {

    @Value("${cross_service_baseurl}")
    private String crossServiceBaseUrl;

    private final InterestMapper interestMapper;

    private final SeekerCrossService seekerCrossService;

    private final RecruiterMapper recruiterMapper;

    private final PhoneNumberUtils phoneNumberUtils;

    private final UserCommonService userCommonService;

    private final AuthConfig authConfig;

    private final RestTemplate restTemplate;

    public RecruiterSeekerServiceImpl(AuthConfig authConfig, RestTemplate restTemplate, InterestMapper interestMapper, UserCommonService userCommonService, SeekerCrossService seekerCrossService, PhoneNumberUtils phoneNumberUtils, RecruiterMapper recruiterMapper) {
        this.authConfig = authConfig;
        this.restTemplate = restTemplate;
        this.interestMapper = interestMapper;
        this.userCommonService = userCommonService;
        this.seekerCrossService = seekerCrossService;
        this.phoneNumberUtils = phoneNumberUtils;
        this.recruiterMapper = recruiterMapper;
    }


    /**
     * @Description: 获取推荐牛人列表，调用方
     * @param req 
     * @return Result<List<RCrossGetGoodSeekerResp>>
     * @Author lhb
     * @CreateTime 2025/7/9 11:34
     */
    @Override
    public Result<RCrossGetGoodSeekersResp> getGoodSeekerList(RCrossGetGoodSeekerListReq req) {
        Recruiter recruiter=TLUtil.get(TLUtil.R);
        Long userId=recruiter.getUserId();
        //获取本公司的userId
        Long companyId = recruiter.getCompanyId();
        List<Recruiter> recruitersByCompanyId = recruiterMapper.getRecruitersByCompanyId(companyId);
        List<Long> recruiterUserIdList = recruitersByCompanyId.stream()
                .map(Recruiter::getUserId)
                .filter(Objects::nonNull)
                .toList();
        //构造请求体
        SCrossGetGoodSeekerListReq sCrossGetGoodSeekerListReq=new SCrossGetGoodSeekerListReq();
        sCrossGetGoodSeekerListReq.setRecruiterUserIdList(recruiterUserIdList);
        BeanUtils.copyProperties(req,sCrossGetGoodSeekerListReq);
        //跨服务调用
        String url = crossServiceBaseUrl + "/seeker/common/getGoodSeekerList";
        // 手动创建 CrossServiceInvoker 实例
        CrossServiceInvoker invoker =
                new CrossServiceInvoker(authConfig, restTemplate);
        Result<Object> result = null;
        try {
            result = invoker.invokeAndHandle(
                    url,
                    HttpMethod.POST,
                    sCrossGetGoodSeekerListReq,
                    Object.class,
                    userId,
                    null
            );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(!result.getCode().equals(HttpServletResponse.SC_CREATED)) {
            throw new IllegalArgumentException("VALIDATION_ERROR：查询失败");
        }
        SCrossGetGoodSeekersResp sCrossGetGoodSeekersResp=JSON.parseObject(JSON.toJSONString(result.getData()),
                SCrossGetGoodSeekersResp.class);
        //初始化响应体
        RCrossGetGoodSeekersResp resp=new RCrossGetGoodSeekersResp();
        resp.setRespList(new ArrayList<>());
        //因为BeanUtils的权限，使用循环构造
        BeanUtils.copyProperties(sCrossGetGoodSeekersResp, resp);
        for (SCrossGetGoodSeekerResp sCrossGetGoodSeekerResp:sCrossGetGoodSeekersResp.getRespList()){
            RCrossGetGoodSeekerResp rCrossGetGoodSeekerResp=new RCrossGetGoodSeekerResp();
            BeanUtils.copyProperties(sCrossGetGoodSeekerResp, rCrossGetGoodSeekerResp);
            resp.getRespList().add(rCrossGetGoodSeekerResp);
        }
        return Result.success(resp);
    }

    /**
     * @Description: 对求职者感兴趣
     * @param userId
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/7/12 15:58
     */
    @Override
    public Result<Object> interestedSeeker(Long userId) {
        Recruiter recruiter = TLUtil.get(TLUtil.R);
        Long recruiterUserId=recruiter.getUserId();
        if(interestMapper.interestSeeker(recruiterUserId,userId)==0) {
            throw new RuntimeException("操作失败");
        }
        String token=userCommonService.updateRedisUserToken(recruiter.getUserId(),RECRUITER_KEY,
                authConfig.getJwtRecruiterSecret(),RECRUITER_TTL, TimeUnit.DAYS);
        if(token==null) throw new RuntimeException("token生成失败");
        return Result.success(token);
    }

    /**
     * @Description:  获取感兴趣列表
     * @return Result<List<InterestedSeekerResp>>
     * @Author lhb
     * @CreateTime 2025/7/12 16:25
     */
    @Override
    public Result<List<InterestedSeekerResp>> getInterestedSeekerList() {
        List<InterestedSeekerResp> respList = new ArrayList<>();
        Long recruiterUserId=TLUtil.get(TLUtil.R).getUserId();
        List<Long> seekerUserIds = interestMapper.getRecord(recruiterUserId);
        if(seekerUserIds.isEmpty()) {
            return Result.success(respList);
        }
        List<User> users = userCommonService.getUsersByUserIds(seekerUserIds);
        List<Seeker> seekers = seekerCrossService.getSeekersByUserIds(seekerUserIds);
        // 将 users 转换为 Map
        Map<Long, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getUserId, user -> user));
        seekers.stream()
                .map(seeker -> {
                    User user = userMap.get(seeker.getUserId());
                    if (user != null) {
                        BeanUtils.copyProperties(user,seeker);
                    }
                    return seeker;
                })
                .toList();
        // 遍历 respList 并设置 name等其他字段
        for (Seeker seeker : seekers) {
            InterestedSeekerResp resp = new InterestedSeekerResp();
            String phone="";
            try {
                phone = phoneNumberUtils.decryptPhone(seeker.getPhoneAes());
                phone = PhoneNumberUtils.maskPhoneNumber(phone);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            resp.setPhone(phone);
            BeanUtils.copyProperties(seeker,resp);
            respList.add(resp);
        }
        return Result.success(respList);
    }
}
